<template>
	<view>
		<view class="outbox">
			<view class="avatar-section">
				<image :src="user.avatar" mode="aspectFit" class="avatar" v-if="user.avatar" />
				<uni-icons v-else type="contact" size="50" color="#ccc" class="default-avatar" />
				<button type="default" @tap="chooseAvatar" class="chooseAvatar">更换头像</button>
			</view>
			<view class="row" v-for="(item, index) in userFields" :key="index">
				<view class="label">{{ item.label }}</view>
				<view v-if="item.component === 'select'" class="input">
					<uni-data-select value="item.options[index].value" :localdata="item.options"
						@change="validateInput(item.field)" />
				</view>
				<!-- 用uniapp 中的日历选择组件 渲染 -->
				<view v-else-if="item.field === 'birthday'" class="input">
					<uni-datetime-picker type v-model="user[item.field]" @confirm="validateInput('birthday')"
						placeholder="请选择出生日期" />
					<view v-if="errorMessage[item.field]" class="error-message">{{ errorMessage[item.field] }}</view>
				</view>
				<!-- 其他 -->
				<view v-else class="input">
					<input :placeholder="item.placeholder" v-model.trim="user[item.field]"
						@input="validateInput(item.field)" :type="item.type || 'text'" />
					<view v-if="errorMessage[item.field]" class="error-message">{{ errorMessage[item.field] }}</view>
				</view>
			</view>
		</view>
		<!-- 提交按钮 -->
		<button type="primary" @tap="submitUserInfo" :disabled="hasErrors">保存修改</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				user: {
					name: '张三',
					gender: '1',
					birthday: '1990-01-01',
					height: '170',
					currentWeight: '80',
					targetWeight: '65',
					avatar: '',
				},
				userFields: [{
						label: '姓名',
						field: 'name',
						placeholder: '请输入您的姓名',
						type: 'text'
					},
					{
						label: '性别',
						field: 'gender',
						component: 'select', // 指定使用选择器组件
						options: [{
								value: '0',
								text: "男生"
							},
							{
								value: "1",
								text: "女生"
							}
						], // 引用上面定义的选项数组
						placeholder: '请选择性别'
					},
					{
						label: '身高',
						field: 'height',
						placeholder: '请输入身高（厘米）',
						type: 'text'
					},
					{
						label: '出生日期',
						field: 'birthday',
						placeholder: 'YYYY-MM-DD',
						type: 'text'
					},
					{
						label: '当前体重',
						field: 'currentWeight',
						placeholder: '请输入你的体重（千克）',
						type: 'text'
					},
					{
						label: '目标体重',
						field: 'targetWeight',
						placeholder: '请输入你的目标体重（千克）',
						type: 'text'
					},

				],
				errorMessage: {}
			};
		},
		computed: {
			hasErrors() {
				return Object.keys(this.errorMessage).length > 0;
			}
		},
		methods: {
			validateInput(field) {
				let message = '';
				switch (field) {
					case 'name':
						message = !this.user.name.trim() ? '用户名不能为空' : '';
						break;
					case 'gender':
						message = !['男', '女'].includes(this.user.gender) ? '请选择性别' : '';
						break;
					case 'birthday':
						const regex = /^\d{4}-\d{2}-\d{2}$/;
						message = !regex.test(this.user.birthday) ? '生日格式不正确（YYYY-MM-DD）' : '';
						break;
					case 'height':
						message = !/^\d+$/.test(this.user.height) || parseInt(this.user.height) < 100 || parseInt(this.user
							.height) > 300 ? '身高请输入100至300之间的数字（单位：厘米）' : '';
						break;
					case 'currentWeight':
					case 'targetWeight':
						message = !/^\d+(\.\d+)?$/.test(this.user[field]) || parseFloat(this.user[field]) <= 0 ?
							'体重必须是大于0的数字（单位：千克）' : '';
						break;
					default:
						break;
				}
				this.errorMessage[field] = message || null;
			},

			submitUserInfo() {
				// 验证逻辑已在输入时实时执行，此处可直接提交或处理其他逻辑
				console.log('提交的用户信息:', this.user);
				uni.showToast({
					title: '信息已保存',
					duration: 1000,
				});
				uni.navigateBack({
					url: '../pages/center/center'
				});

			},
			chooseAvatar() {
				uni.chooseImage({
					count: 1, // 限制选择一张图片
					sizeType: ['original', 'compressed'], // 原图或压缩图
					success: (res) => {
						// 用户选择完图片后的回调
						const tempFilePath = res.tempFilePaths[0]; // 获取临时文件路径
						// 这里可以上传图片到服务器并获取URL，然后更新user.avatar
						this.user.avatar = tempFilePath;
					},
				});
			},
			maskClick(e) {
				console.log('maskClick事件:', e);
			}
		}
	};
</script>
<style scoped>
	.outbox {
		padding: 16px;
	}

	.row {
		display: flex;
		flex-direction: column;
		margin-bottom: 12px;
	}

	.label {
		font-size: 14px;
		color: #333;
		margin-bottom: 4px;
	}

	.input {
		position: relative;
		width: 100%;
	}

	.input input {
		padding: 8px 12px;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 14px;
		width: 100%;
	}

	.error-message {
		color: #f00;
		font-size: 12px;
		margin-top: 4px;
	}

	button[type="primary"] {
		background-color: #007bff;
		border: none;
		color: white;
		padding: 10px 16px;
		text-align: center;
		text-decoration: none;
		display: inline-block;
		font-size: 14px;
		/* margin: 16px 0; */
		cursor: pointer;
		border-radius: 4px;
		opacity: 1;
		transition: 0.3s;
		position: fixed;
		left: 38%;
		bottom: 0px;
	}

	button[type="primary"]:disabled {
		opacity: 0.6;
		cursor: not-allowed;
	}

	.avatar-row {
		display: flex;
		align-items: center;
		margin-bottom: 12px;
	}

	.avatar {
		width: 100px;
		height: 100px;
		border-radius: 50%;
		margin-right: 16px;
	}

	.chooseAvatar {
		width: 280rpx;
		height: 100rpx;
		display: inline-block;
		float: right;
		font-size: 20px;
		margin: 0px auto;
	}
</style>